package team.dmh.wx.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @Auther: Hz1kai
 * @Date: 2018/10/14 20:08
 * @Description:
 */
public class WSServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //每个channel都有一个pipeline，在其中添加handler组成处理器链
        ChannelPipeline pipeline=socketChannel.pipeline();
        //WebSocket基于http协议，所以要设置编解码器（HttpRequestDecoder, HttpResponseEncoder）
        pipeline.addLast(new HttpServerCodec());
        //对写大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        //对HttpMessage的聚合，包括FullHttpResponse和FullHttpRequest，设置最大内容长度
        pipeline.addLast(new HttpObjectAggregator(1024*64));
        //配置开启WebSocketServer和连接路径
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        //配置心跳处理器 60s无操作则为读写空闲，触发heartBeatHandler的用户
        pipeline.addLast(new IdleStateHandler(600,600,1200));
        pipeline.addLast(new HeartBeatHandler());
        //配置自定义Handler
        pipeline.addLast(new ChatHandler());
    }
}
